<template>
  <teleport to="body">
    <div v-if="_show" class="fullscreen-container" :style="{ zIndex: +zIndex + 1 }">
      <div class="dialog" :style="{ width, maxHeight: height }" :class="{ 'full-screen': height === '100vh' }">
        <van-icon
          v-if="!noHeader"
          name="cross"
          color="#c8c9cc"
          size="6vw"
          class="close-btn"
          @click="onCloseDialog"
        />
        <div class="dialog-title" :style="{ display: noHeader ? 'none' : 'block' }">{{ title }}</div>
        <div class="dialog-body" :style="{ maxHeight: dialogBodyHeight }">
          <slot name="dialog-body"></slot>
        </div>
      </div>
    </div>
    <van-overlay id="overlay" :show="_show" :z-index="zIndex" :lock-scroll="false" />
  </teleport>
</template>

<script setup lang="ts">
import { useRouterStore } from '@/framework/store/router'

const props = withDefaults(
  defineProps<{
    width?: string
    height?: string
    title?: string
    show: boolean
    noHeader?: boolean
    zIndex: string
  }>(),
  {
    width: '92vw',
    height: '95vh',
    title: '',
    noHeader: false,
    zIndex: '100'
  }
)

let _show = ref(false)
let dialogBodyHeight = ref('0px')
const routerStore = useRouterStore()
const { width, height, title, show } = toRefs(props)
const emit = defineEmits<{ (e: 'update:show', show: boolean): void }>()

watch(
  () => show.value,
  (value) => {
    _show.value = value
    nextTick(calcDialogBodyHeight)
  }
)

const onCloseDialog = () => {
  _show.value = false
  emit('update:show', false)
}

watch(
  () => _show.value,
  () => routerStore.blockReturn(_show.value, onCloseDialog),
  { immediate: true }
)

const calcDialogBodyHeight = () => {
  const dialogTitleDOM = document.querySelector('.dialog-title')
  if (!dialogTitleDOM) return
  const dialogTitleHeight = dialogTitleDOM.scrollHeight + 'px'
  dialogBodyHeight.value = `calc(${height.value} - ${dialogTitleHeight} - 3vh)`
}
</script>

<style scoped>
.fullscreen-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog {
  background-color: #fff;
  border-radius: 15px;
  box-sizing: border-box;
  padding: 5vw 0;
  z-index: 101;
  overflow: hidden;
}
.close-btn {
  float: right;
  margin-right: 5vw;
}
.dialog-title {
  width: calc(100% - 10vw);
  margin: 0 auto;
  font-size: 5vw;
  line-height: 6vw;
  text-align: center;
  padding-bottom: 2vh;
}
.dialog-body {
  overflow: auto;
  background-color: #fff;
  padding-bottom: 2vh;
  box-sizing: border-box;
}
.full-screen {
  height: 100vh;
  border-radius: 0 !important;
}
</style>
